package cn.tedu._03vehicle.base.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class CountCheckInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUEST_COUNT = 3;
    private static final int MAX_REQUEST_WINDOW_SIZE = 60;

    private final ConcurrentHashMap<String,Integer> clientCount = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String,LocalDateTime> lastResetTime = new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("开始执行访问次数检查...");
        String ip = request.getRemoteAddr();
        LocalDateTime lastTime = lastResetTime.get(ip);
        if(lastTime == null || LocalDateTime.now().isAfter(lastTime.plusSeconds(MAX_REQUEST_WINDOW_SIZE))){
            clientCount.put(ip,0);
            lastResetTime.put(ip,LocalDateTime.now());
        }
        if(clientCount.get(ip) >= MAX_REQUEST_COUNT){
            log.debug("访问次数过多，被拒绝访问...");
            throw new RuntimeException("访问次数过多");
        }

        int count = clientCount.get(ip);
        count++;
        clientCount.put(ip,count);
        return true;
    }
}
